<template>
  <div>
    <NavBar></NavBar>
    <div class="body">
      <div class="container">
        <div class="content-head">
          <div class="bg-head"></div>
          <div class="msg-head">
            <div class="avatar-body">
              <el-upload
              :action="uplaodUrl"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="user-msg">
              <p class="user-name">{{userName}}</p>
              <p>
                <span>{{age}}岁</span>&nbsp;&nbsp;
                <span>
                  <el-tag type="primary" v-if="sex == 0"><i class="el-icon-male"></i></el-tag>
                  <el-tag type="danger" v-if="sex == 1"><i class="el-icon-female"></i></el-tag>
                </span>&nbsp;&nbsp;
                <span>获赞:&nbsp;&nbsp;<el-tag type="danger"><i class="el-icon-star-on"></i>{{receiveCount}}</el-tag></span>
              </p>
            </div>
            <div class="edit-data">
              <el-button plain type="primary" @click="toEdit">
                <span v-if="!isEdit">编辑个人资料</span>
                <span v-if="isEdit">返回我的主页</span>
              </el-button>
            </div>
          </div>
        </div>
        <div class="content-body">
          <div v-if="!isEdit">
            <el-row>
              <el-col :span="15">
                <div class="content-left">
                  <el-tabs v-model="activeName">
                    <el-tab-pane label="动态" name="first">
                      <!-- 我的动态 -->
                      <div class="answer-list-container" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="1">
                        <div class="list-body" v-for="(item, index) in likeAnswerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>
                                  <el-button type="primary" v-show="item.like" disabled>{{item.likeCount}}&nbsp;已赞同</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="回答" name="second">
                      <div class="answer-list-container" v-infinite-scroll="loadMore1" infinite-scroll-disabled="busy1" infinite-scroll-distance="1">
                        <div class="list-body" v-for="(item, index) in answerList" :key="index">
                          <div>
                            <span class="del-btn"><el-button @click="delAnswer(item.id)" type="danger">删除</el-button></span>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>

                                  <el-button type="primary" size="small" icon="el-icon-caret-top" disabled >已赞同{{item.likeCount}}</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="提问" name="third">
                      <div class="question-container" v-infinite-scroll="loadMore2" infinite-scroll-disabled="busy2" infinite-scroll-distance="1">
                        <div class="question-body" v-for="(item, index) in questionList" :key="index">
                          <span class="del-btn"><el-button @click="delQuestion(item.id)" type="danger">删除</el-button></span>
                          <h3 @click="toAnswerDetail(item.id)">{{item.questionName}}</h3>
                          <p><el-tag type="primary">{{item.modularName}}</el-tag></p>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="收藏" name="forth">
                      <div class="answer-list-container">
                        <div class="list-body" v-for="(item, index) in collectAnswerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>
                                  <el-button type="success" v-show="item.collect" disabled>已收藏</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="关注" name="fifth">
                      <div class="follow-container">
                        <div v-for="(item,index) in userList" :key="index">
                          <div class="follow-body">
                            <span>
                              <span class="user-avatar">
                                <img :src="item.avatar" alt="">
                              </span>
                            </span>
                            <span class="user-name" @click="toUserDetail(item.id)">
                              <span>
                                {{item.name}}
                              </span>
                            </span>
                            <span class="user-btn">
                              <el-button type="success" @click="unFollowUser(item.id)" v-show="item.follow">已关注</el-button>
                              <el-button type="primary" @click="followUser(item.id)" v-show="!item.follow">+ 关注</el-button>
                            </span>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="关注者的回答" name="sixth">
                      <div class="answer-list-container">
                        <div class="list-body" v-for="(item, index) in followAnswerList" :key="index">
                          <div>
                            <h3 class="answer-header" @click="toAnswerDetail(item.questionId,item.userId)">{{item.questionName}}</h3>
                              <p class="answer-body" v-html="item.answerMessage"></p>
                              <div class="answer-footer">
                                <span>
                                  <el-tag type="primary">{{item.modularName}}</el-tag>
                                </span>
                                <span>
                                  <el-button type="success" v-show="item.collect" disabled>已收藏</el-button>
                                </span>
                              </div>
                          </div>
                        </div>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-col>
              <el-col :span="8" :offset="1">
                <div class="content-right">
                  <div class="number-board">
                    <div class="follow-num board-content">
                      <span>关注了</span>
                      <p>{{followCount}}</p>
                    </div>
                    <div class="fan-num board-content">
                      <span>粉丝</span>
                      <p>{{fanCount}}</p>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
          <div v-if="isEdit">
            <div class="edit-content">
              <el-form ref="formData" :model="formData" label-width="100px">
                <el-form-item label="昵称:">
                  <el-input v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="手机号:">
                  <el-input v-model="formData.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱:">
                  <el-input v-model="formData.email"></el-input>
                </el-form-item>
                <el-form-item label="年龄:">
                  <el-input v-model="formData.age"></el-input>
                </el-form-item>
                <el-form-item label="性别:">
                  <el-radio-group v-model="formData.sex">
                    <el-radio :label="0">男</el-radio>
                    <el-radio :label="1">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item class="btn-group">
                  <el-button type="primary" @click="editData">修改</el-button>
                  <el-button type="danger" @click="changePassDialog = true">修改密码</el-button>
                </el-form-item>
              </el-form>
              <el-dialog title="修改密码" :visible.sync="changePassDialog" width="30%">
                <el-form :model="formData2" label-width="60px">
                  <el-form-item label="新密码:">
                    <el-input v-model="formData2.password" style="width:200px;"></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="changePassDialog = false">取 消</el-button>
                  <el-button type="primary" @click="changePass">确 定</el-button>
                </div>
              </el-dialog>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="toTop">
      <el-button @click="toTop" icon="el-icon-top" type="primary">回到顶部</el-button>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar'
import axios from 'axios'
export default {
  name: 'UserPage',
  components: {
    NavBar
  },
  data () {
    return {
      followCount: '',
      fanCount: '',
      changePassDialog: false,
      userList: [],
      likeAnswerList: [],
      collectAnswerList: [],
      followAnswerList: [],
      questionList: [],
      answerList: [],
      formData: {
        id: '',
        name: '',
        phone: '',
        email: '',
        sex: '',
        age: ''
      },
      formData2: {
        id: '',
        password: ''
      },
      isEdit: false,
      activeName: 'first',
      imageUrl: '',
      userName: '',
      age: '',
      receiveCount: '',
      sex: '',
      userId: this.$route.query.id,
      loginId: localStorage.getItem('userId'),
      busy: false,
      busy1: false,
      busy2: false,
      page: 1,
      page1: 1,
      page2: 1,
      finalPage: 1,
      finalPage1: 1,
      finalPage2: 1
    }
  },
  created () {
    this.getInfo()
    this.showLike(1)
    this.showMyAnswer(1)
    this.showMyQuestion(1)
    this.showCollect()
    this.showUserList()
    this.showMyFollow()
    this.uplaodUrl = '/api/user/uploadFace?userId=' + this.userId
  },
  methods: {
    toTop () {
      var top = document.body.scrollTop || document.documentElement.scrollTop
      scrollBy(0, -top)
    },
    loadMore () {
      if (this.finalPage > this.page) {
        this.busy = true
        this.page++
        this.showLike(this.page)
        setTimeout(() => {
        // 这里请求接口去拿数据，实际应该是调用一个请求数据的方法
          this.busy = false
        }, 1000)
      } else {
        this.busy = false
      }
    },
    loadMore1 () {
      if (this.finalPage1 > this.page1) {
        this.busy1 = true
        this.page1++
        this.showMyAnswer(this.page1)
        setTimeout(() => {
        // 这里请求接口去拿数据，实际应该是调用一个请求数据的方法
          this.busy1 = false
        }, 1000)
      } else {
        this.busy1 = false
      }
    },
    loadMore2 () {
      if (this.finalPage2 > this.page2) {
        this.busy2 = true
        this.page2++
        this.showMyQuestion(this.page2)
        setTimeout(() => {
        // 这里请求接口去拿数据，实际应该是调用一个请求数据的方法
          this.busy2 = false
        }, 1000)
      } else {
        this.busy2 = false
      }
    },
    delAnswer (id) {
      this.$confirm('确定删除回答？').then(() => {
        axios.get('/api/answer/delAnswer?id=' + id).then(res => {
          this.$notify({
            title: 'success',
            type: 'success',
            message: res.data.data
          })
          this.showMyAnswer(1)
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },
    delQuestion (id) {
      this.$confirm('确定删除问题？').then(() => {
        axios.get('/api/question/delQuestion?qid=' + id).then(res => {
          this.$notify({
            title: 'success',
            type: 'success',
            message: res.data.data
          })
          this.showMyQuestion(1)
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },
    toEdit () {
      this.isEdit = !this.isEdit
    },
    changePass () {
      axios({
        url: '/api/user/updateUser',
        method: 'post',
        data: this.formData2
      }).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.changePassDialog = false
        this.isEdit = false
      }).catch(err => {
        console.log(err)
      })
    },
    editData () {
      axios({
        url: '/api/user/updateUser',
        method: 'post',
        data: this.formData
      }).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.isEdit = false
        this.getInfo()
      }).catch(err => {
        console.log(err)
      })
    },
    toAnswerDetail (...param) {
      console.log(param)
      if (param[1]) {
        this.$router.push('/answer-detail?id=' + param[0] + '&creator=' + param[1])
      } else {
        this.$router.push('/answer-detail?id=' + param[0])
      }
      // answer_detail
    },
    showCollect () {
      axios.get('/api/user/showUserCollect?userId=' + this.userId).then(res => {
        this.collectAnswerList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    showMyFollow () {
      axios.get('/api/user/showUserFollow?userId=' + this.userId).then(res => {
        this.followAnswerList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    showLike () {
      axios.get('/api/user/showUserLike?userId=' + this.userId).then(res => {
        this.likeAnswerList = res.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    showMyAnswer (page) {
      axios.get('/api/answer/queryAnswerList?userId=' + this.userId + '&page=' + page).then(res => {
        const resData = res.data.data.pagedResult.rows
        this.finalPage1 = res.data.data.pagedResult.total
        this.answerList = page === 1 ? resData : this.answerList.concat(resData)
      }).catch(err => {
        console.log(err)
      })
    },
    showMyQuestion (page) {
      console.log('showQuestion')
      axios.get('/api/question/questionList?userId=' + this.userId + '&page=' + page).then(res => {
        const resData = res.data.data.rows
        this.finalPage1 = res.data.data.total
        this.questionList = page === 1 ? resData : this.questionList.concat(resData)
      }).catch(err => {
        console.log(err)
      })
    },
    showUserList () {
      axios.get('/api/user/userList?userId=' + localStorage.getItem('userId')).then(res => {
        this.userList = res.data.data.filter(item => item.id !== localStorage.getItem('userId'))
        this.userList.map(item => {
          item.avatar = 'http://127.0.0.1:9901' + item.avatar
        })
      }).catch(err => {
        console.log(err)
      })
    },
    followUser (id) {
      axios.get('/api/user/beFans?userId=' + id + '&fanId=' + localStorage.getItem('userId')).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.showUserList()
        this.getInfo()
      }).catch(err => {
        console.log(err)
      })
    },
    unFollowUser (id) {
      axios.get('/api/user/nobeFans?userId=' + id + '&fanId=' + localStorage.getItem('userId')).then(res => {
        this.$notify({
          title: '成功',
          message: res.data.data,
          type: 'success'
        })
        this.showUserList()
        this.getInfo()
      }).catch(err => {
        console.log(err)
      })
    },
    handleSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.getInfo()
      this.$notify.success('图片上传成功')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    toUserDetail (id) {
      console.log(id)
      this.$router.push('/user-detail?id=' + id)
    },
    getInfo () {
      axios.get('/api/user/queryUser?id=' + this.userId)
        .then(res => {
          this.imageUrl = 'http://127.0.0.1:9901' + res.data.data.avatar
          this.userName = res.data.data.name
          this.age = res.data.data.age
          this.sex = res.data.data.sex
          this.formData.id = res.data.data.id
          this.formData.name = res.data.data.name
          this.formData.phone = res.data.data.phone
          this.formData.email = res.data.data.email
          this.formData.age = res.data.data.age
          this.formData.sex = res.data.data.sex
          this.formData2.id = res.data.data.id
          this.fanCount = res.data.data.fanCount
          this.followCount = res.data.data.followCount
          this.receiveCount = res.data.data.receiveCount
        })
        .catch(err => {
          console.log(err)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.body{
  width: 100%;
  background: #f6f6f6;
  min-height: 1000px;
  height: auto;
  padding-top: 90px;
  .container {
    width: 70%;
    margin: 0 auto;
    min-height: 800px;
    height: auto;
    padding-bottom: 20px;
    // border: 1px solid #000;
    .content-head {
      width: 100%;
      height: 300px;
      box-shadow: 0 1px 3px rgba(26,26,26,.1);
      border-radius: 2px;
      background: #fff;
      .bg-head {
        width: 100%;
        height: 150px;
        background: #ccc;
      }
      .msg-head {
        width: 100%;
        height: 150px;
        .avatar-body {
          display: inline-block;
          width: 188px;
          height: 178px;
          padding: 5px;
          border-radius: 8px;
          background: #fff;
          position: relative;
          bottom: 80px;
          left: 30px;
        }
        .user-msg {
          display: inline-block;
          width: 200px;
          position: relative;
          bottom: 100px;
          left: 60px;
          .user-name {
            font-size: 24px;
            font-weight: bold;
          }
        }
        .edit-data {
          float: right;
          position: relative;
          top: 70px;
          right: 20px;
        }
      }
    }
    .content-body {
      margin-top: 20px;
      .content-left {
        padding: 10px;
        background: #fff;
        .answer-list-container {
          width: 100%;
          .list-body {
            padding: 10px;
            border-bottom: 1px solid #f0f2f7;
            width: 100%;
            .del-btn {
              float: right;
            }
            .answer-header {
              cursor: pointer;
            }
            .answer-body {
              width: 80%;
              height: auto;
              line-height: 30px;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              // white-space: nowrap;
            }
            .answer-footer span{
              margin-right: 3%;
            }
          }
        }
        .question-container {
          .question-body {
            padding: 10px;
            border-bottom: 1px solid #f0f2f7;
            width: 100%;
            .del-btn {
              float: right;
            }
            h3{
              cursor: pointer;
            }
          }
        }
        .follow-container {
          width: 100%;
          .follow-body {
            width: 100%;
            // padding: 7px;
            height: 60px;
            border-bottom: 1px solid #f0f2f7;
            line-height: 50px;
            .user-avatar {
              width: 50px;
              height: 50px;
              border-radius: 50%;
              display: inline-block;
              border: 1px solid #efefef;
              img {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                vertical-align: top;
              }
            }
            .user-name {
              width: 100px;
              display: inline-block;
              cursor: pointer;
            }
            .user-btn {
              float: right;
              position: relative;
              right: 10px;
            }
          }
        }
      }
      .content-right {
        width: 100%;
        .number-board {
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #fff;
          height: 100px;
          padding-top: 20px;
          .follow-num {
            border-right: 2px #efefef solid;
          }
          .board-content {
            width: 50%;
            text-align: center;
            line-height: 10px;
            span {
              color: #8590a6;
            }
            p {
              font-size: 20px;
              font-weight: bold;
            }
          }

        }
      }
      .edit-content {
        background: #fff;
        padding: 10px;
        width: 100%;
        .el-form {
          width: 50%;
          margin: 0 auto;
        }
        .el-input {
          width: 400px;
        }
        .btn-group {
          .el-button {
            width: 100px;
          }
        }
      }
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 3px;
}
.toTop {
  position: fixed;
  bottom: 10px;
  right: 20px;
}
</style>
